package com.example.demo.controller;

import com.example.demo.enity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@CrossOrigin
@RestController
public class StudentHandler {
    @Autowired
    RedisTemplate redisTemplate;

    //添加数据
    @PostMapping("/set")
    //request将json对象转为java对象
    public void set(@RequestBody Student student){
       redisTemplate.opsForValue().set("student",student);

    }

    //获取数据
    @GetMapping("/get/{key}")
    public Student get(@PathVariable String key){
        return (Student) redisTemplate.opsForValue().get(key);
    }

    //删除数据
    @DeleteMapping("/delete/{key}")
    public Boolean delete(@PathVariable String key){
       redisTemplate.delete(key);
       return redisTemplate.hasKey(key);
    }

    //存储字符串并取出字符串
    @GetMapping("/str")
    public String getStr(){
        redisTemplate.opsForValue().set("name","李铭晗");
        return (String) redisTemplate.opsForValue().get("name");
    }

    //存储列表的值并获取列表
    @GetMapping("/students")
    public List<Student> getStudents(){
        List<Student> students=Student.getStudents();
        ListOperations<String,Student> operations=redisTemplate.opsForList();
        if(!redisTemplate.hasKey("stus")){
          for(Student student:students){
            operations.rightPush("stus",student);
          }
        }
        return operations.range("stus",0,-1);
    }
    //操作集合
    @GetMapping("/set2")
    public Set<String> getSet(){
        SetOperations<String,String> setOperations=redisTemplate.opsForSet();
        setOperations.add("set","c");
        setOperations.add("set","html,css");
        setOperations.add("set","php");
        setOperations.add("set","java");
        setOperations.add("set","python");
        setOperations.add("set","java");
        setOperations.add("set","js");
        return  setOperations.members("set");
    }
    //操作有序集合
    @GetMapping("/zset")
    public Set<String> getZset(){
        ZSetOperations<String,String> zSetOperations=redisTemplate.opsForZSet();
        zSetOperations.add("zset","java",2);
        zSetOperations.add("zset","sql",1);
        zSetOperations.add("zset","python",3);
        return zSetOperations.range("zset",0,-1);
    }

    //操作Hashmap
    @GetMapping("/hashSet")
    public String getHashSet(){
        HashOperations<String,String,String> hashOperations=redisTemplate.opsForHash();
        //存入数据
        hashOperations.put("study","java","spring");
        //返回数据
        return  hashOperations.get("study","java");
    }
}
